package cn.net.xyan.easy.gwt.client.ui;

import cn.net.xyan.easy.gwt.client.event.Action;
import cn.net.xyan.easy.gwt.client.event.ActionEvent;
import cn.net.xyan.easy.gwt.client.event.ActionEventBus;
import cn.net.xyan.easy.gwt.client.event.ActionHandler;
import cn.net.xyan.easy.gwt.client.model.MenuItemModel;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import org.gwtbootstrap3.client.ui.NavPills;
import org.gwtbootstrap3.client.ui.base.AbstractListItem;

/**
 * Created by zarra on 16/2/17.
 */
public class SideBar extends Composite {

    DockLayoutPanel panel;

    NavPills pills;
    AbstractListItem prevListItem;


    private void setupUI(){
        pills = new NavPills();
        pills.setStacked(true);
        panel = new DockLayoutPanel(Style.Unit.PX);
        panel.add(pills);

        addActionEventHandler(new ActionHandler<MenuItemModel>() {
            public void onAction(Action<MenuItemModel> action) {
                AbstractListItem listItem = (AbstractListItem) action.getWidget();
                if (listItem!=null){

                    if (prevListItem!=null && prevListItem!=listItem){
                        prevListItem.setActive(false);
                    }

                    listItem.setActive(true);

                    prevListItem = listItem;


                }
            }
        });
    }

    public void addItem(MenuItemModel model){
        Menu menu = new Menu(model);
        pills.add(menu);
    }

    public SideBar(){
        setupUI();
        if (panel!= null)
            initWidget(panel);
    }

    public HandlerRegistration addActionEventHandler(ActionHandler<MenuItemModel> handler){
        return ActionEventBus.eventBus().addHandler(ActionEvent.getType(MenuItemModel.class),handler);
        //return addHandler(handler, ActionEvent.getType(MenuItemModel.class));
    }
}
